package org.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.entity.Permission;
import org.example.entity.RolePermission;
import org.example.service.IPermissionService;
import org.example.service.IRolePermissionService;
import org.example.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author guocb
 * @since 2021-03-01
 */
@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    IRoleService roleService;

    @Autowired
    IPermissionService permissionService;

    @Autowired
    IRolePermissionService rolePermissionService;

    @GetMapping("/list")
    public String list(Model model){
        model.addAttribute("roleList",roleService.list());
        return "rolelist";
    }

    //跳转权限管理页面
    @GetMapping("/permission")
    public String permission(Long roleId,Model model){

        List<Permission> permissionAllList = permissionService.selectRolePermission(roleId);
        //先查一级
        List<Permission> permissionList = new ArrayList<>();//permissionService.list(new QueryWrapper<Permission>().eq(Permission.PARENTID, 0));
        for (Permission permission : permissionAllList) {
            if(permission.getParentId() == 0){
                for (Permission subPerm : permissionAllList) {
                    if(subPerm.getParentId() == permission.getId()){
                        //添加到一级菜单的子菜单集合
                        permission.getPermissions().add(subPerm);
                    }
                }
                //一级
                permissionList.add(permission);
            }
        }
        model.addAttribute("permissionList",permissionList);
        model.addAttribute("roleId",roleId);
        return "permission";
    }


    @PostMapping("/addPerm")
    public String addPerm(Long roleId,Long [] permissionIds,Model model){
        //删除原有的权限
        rolePermissionService.remove(new QueryWrapper<RolePermission>().eq(RolePermission.ROLEID,roleId));
        //添加新权限
        Collection<RolePermission> rolePermissions = new ArrayList<>();
        for (Long permissionId : permissionIds) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId.intValue());
            rolePermission.setPermissionId(permissionId.intValue());
            rolePermissions.add(rolePermission);
        }
        rolePermissionService.saveBatch(rolePermissions);
        return "redirect:list";
    }
}
